import os
import time

import psutil


def kill_old_instances():
    current_pid = os.getpid()
    current_process = psutil.Process(current_pid)
    current_name = current_process.name().lower()  # 适配不同系统的大小写

    # 遍历所有进程
    for proc in psutil.process_iter(['pid', 'name']):
        try:
            proc_info = proc.info
            proc_name = proc_info['name'].lower()
            proc_pid = proc_info['pid']

            # 匹配同名进程且排除自身
            if proc_name == current_name and proc_pid != current_pid:
                proc.terminate()  # 尝试优雅终止
                time.sleep(0.5)  # 等待进程退出
                if proc.is_running():
                    proc.kill()  # 强制终止
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
